<?php


namespace app\user\logic;

//分享链接相关的逻辑
use app\admin\model\Account;
use app\common\model\MiniApp as MiniAppModel;
use app\common\model\Setting;
use app\common\model\WechatShareLink as WechatShareLinkModel;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use EasyWeChat\Kernel\Messages\Article;
use GuzzleHttp\Exception\GuzzleException;
use think\Db;
use think\facade\Cache;
use think\facade\Config;
use think\facade\Env;
use think\facade\Request;

class ShareLinkLogic
{

    //添加链接的播放次数
    public static function addViews($url_no)
    {
       $res= Db::table('wechat_share_link')
            ->where('no', $url_no)
            ->setInc('views');

       return $res;
    }

    //检查今天生成的链接数是否已经超标了
    public static function checkMaxLink($user_id){

        $count=WechatShareLinkModel::where([
            ['created_id','=',$user_id],
            ['add_time','>',today()[0]],
            ['add_time','<',today()[1]],
        ])->count('id');

        $user=\app\user\model\User::get($user_id);
        //获取设置
        $setting=Setting::getAllSetting();

        //判断链接
        if($user->vip==1 || $user->vip==2){
            if($count>=$setting['vip_max_link']){
                //生成的链接已经到达了上限
                return false;
            }
        }else{
            if($count>=$setting['user_max_link']){
                //生成的链接已经到达了上限
                return false;
            }
        }

        //没到上限
        return true;
    }

    // 获取阅读原文url
    public static function getContentSourceUrl()
    {
        //原文的链接地址
        $content_source_url=Setting::where('name','content_source_url')->value('data');

        //存在值就返回，不存在就给默认值
        if($content_source_url){
            return $content_source_url;
        }else{
            return 'https://mp.weixin.qq.com/s/IAFxRMQAJ6fPojmEnGfVTw';
        }
    }

    // 获取分享的id
    public static function getCoverMediaId()
    {
        $media_id = Cache::get('cover_media_id');

        if ($media_id) {
            return $media_id;
        } else {
            //获取数据库公众号，配置文件
            //$config = Config::get('miniprogram.officialAccount');
            $config = self::getAccount();
            $app = Factory::officialAccount($config);
            $result22 = $app->material->uploadImage(Env::get('config_path') . 'yingshi_btn.jpg');
            $media_id = $result22->media_id;
            Cache::set('cover_media_id', $media_id, 5 * 60);
            return $media_id;
        }
    }

    // 读取公众号
    public static function getAccount(){

      return  Config::get('miniprogram.officialAccount');
        //读取后台所有公众号
        $account = Account::field(['app_id','app_secret as secret'])->order('id','asc')->all()->toArray();
        foreach ($account as &$item){
            $item['response_type'] = 'object';
            $account_id = Db::table('account_status')
                ->where([
                    ['app_id', '=', $item['app_id']],
                    ['add_time', 'BETWEEN', today()]
                ])->find();
            //如果超过阅读量
            if(!empty($account_id)){
                continue;
            }else{
                return $item;
            }
        }
        //默认值
        return Config::get('miniprogram.officialAccount');
    }

    public static function getPushOpenids()
    {

        $openids = Cache::get('openids');

        if ($openids) {
//            $this->result(json_decode($openids),200);
            return   json_decode($openids) ;
        } else {
            $app = Factory::officialAccount(ShareLinkLogic::getAccount());
            $list= $app->user->list();  // $nextOpenId 可选
            $list= $list->data->openid;

            if(count($list)<2){
                exception('公众号关注人数低于两人');
            }

            $openids=[$list[0],$list[1]];

            Cache::set('openids', json_encode($openids));
//            $this->result($openids,200);
            return $openids;
        }
    }


    //获取素材的短连接
    private function getLongUrl($long_url)
    {

        $curl = curl_init();
//        $long_url=   "http://mp.weixin.qq.com/s?__biz=MzI5MDQyMTEzMw==&mid=100000058&idx=1&sn=df035850513c96a8e8a92077a955b274&chksm=6c2161d85b56e8ceea93a7d32b18f83e00243b9ccc33e4f9f53eb08d4d435d607a763945ed0c#rd";

        $post_url = "https://mp.weixin.qq.com/mp/appmsg_weapp?action=batch_get_weapp&" . substr($long_url, 26);

        curl_setopt_array($curl, array(
//            CURLOPT_URL => "https://mp.weixin.qq.com/mp/appmsg_weapp?action=batch_get_weapp&__biz=MzI5MDQyMTEzMw==",
            CURLOPT_URL => $post_url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "GET",
            CURLOPT_HTTPHEADER => array(
                "referer: " . $long_url,
                "Cookie: rewardsn=; wxtokenkey=777"
            ),
        ));

        $response = curl_exec($curl);
        curl_close($curl);
        $obj = json_decode($response);

        return $obj->appmsg_compact_url;
//        $this->result( $obj,200);
//        echo $response;
    }



    //生成一个文章的content部分
    public static function getArticleContent($mini_app, $path, $user_id)
    {
        $mini_app_code = $mini_app->code;
        $cover =self::getTestArticleBtnCover();
        $platform_appid=Config::get('miniprogram.wx.appid');
        $content="<a class=\"weapp_text_link\" data-miniprogram-appid=\"$mini_app->wx_appid\"
data-miniprogram-nickname=\"$mini_app->name\"
data-miniprogram-path=\"$path\"
data-miniprogram-servicetype=\"\"
data-miniprogram-type=\"text\" href=\"\" style=\"display: flex;
    align-items: center;
    justify-content: center;
      width:90vw;
    height:38vw;
     background-image: url($cover);
    background-repeat: no-repeat;
    background-size: contain;
    background-position: center;\">
<label  ></label>
</a>
<p style=\"display:flex;justify-content:center;align-items:center;margin-top:15px;\">
    <a class=\"weapp_text_link\" style=\"font-size:12px;\"  data-miniprogram-appid=\"$platform_appid\"
    data-miniprogram-path=\"pages/index/index?lv_1_id=$user_id\" data-miniprogram-nickname=\"变现小程序\" href=\"\" data-miniprogram-type=\"text\"  >
        加入创作团队，进行流量变现
    </a>
</p>";
        return $content;
    }


    //获取测试类的文章封面封面
    public static function getTestArticleBtnCover()
    {
        $test_cover_url = Cache::get('test_cover_url');

        if ($test_cover_url) {
            return $test_cover_url;
        } else {
            //获取数据库公众号，配置文件
            //$config = Config::get('miniprogram.officialAccount');
            $config = self::getAccount();
            $app = Factory::officialAccount($config);
            $result22 = $app->material->uploadImage(Env::get('config_path') . 'test_cover.jpg');
            $media_id = $result22->media_id;
            $test_cover_url = $result22->url;
            Cache::set('test_cover_url', $test_cover_url, 10 * 60);
            return $test_cover_url;
        }
    }

    //获取视频文章封面封面
    public static function getVideoArticleBtnCover()
    {
        $cover_url = Cache::get('cover_url');

        if ($cover_url) {
            return $cover_url;
        } else {
            //获取数据库公众号，配置文件
            //$config = Config::get('miniprogram.officialAccount');
            $config = self::getAccount();
            $app = Factory::officialAccount($config);
           
            $result22 = $app->material->uploadArticleImage(Env::get('config_path') . 'yingshi_btn.jpg');
             
            $media_id = $result22->media_id;
            $cover_url = $result22->url;
            Cache::set('cover_url', $cover_url, 10 * 60);
            return $cover_url;
        }
    }

    //生成一个视频文章的content部分
    public static function getVideoArticleContent($mini_app, $path, $user_id)
    {
        $mini_app_code = $mini_app->code;
        $cover =self::getVideoArticleBtnCover();
        $platform_appid=Config::get('miniprogram.wx.appid');

        $content="<a class=\"weapp_text_link\" data-miniprogram-appid=\"$mini_app->wx_appid\"
data-miniprogram-nickname=\"$mini_app->name\"
data-miniprogram-path=\"$path\"
data-miniprogram-servicetype=\"\"
data-miniprogram-type=\"text\" href=\"\" style=\"display: flex;
    align-items: center;
    justify-content: center;
    width:90vw;
    height:38vw;
    background-image: url($cover);
     background-repeat: no-repeat;
    background-size: contain;
    background-position: center;\">
</a>
<p style=\"display:flex;justify-content:center;align-items:center;margin-top:15px;\">
    <a class=\"weapp_text_link\" style=\"font-size:12px;\"  data-miniprogram-appid=\"$platform_appid\"
    data-miniprogram-path=\"pages/index/index?lv_1_id=$user_id\" data-miniprogram-nickname=\"变现小程序\" href=\"\" data-miniprogram-type=\"text\"  >
        加入创作团队，进行流量变现
    </a>
</p>
";

        return $content;
    }

    //生成素材链接
    public static function createMaterial()
    {

    }

}
